package com.yylending.las.repay.repaydetail;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.Loader;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;
import com.yyfax.infrastructure.mvp.Presenter;
import com.yyfax.infrastructure.mvp.PresenterLoader;
import com.yylending.las.R;
import com.yylending.las.base.BaseActivity;
import com.yylending.las.base.BaseFragment;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;

/**
 * 还款详情
 * Created by ying_he on 2017/7/8.<br>
 * Copyright  2017 www.yylending.com. All Rights Reserved.<br><br>
 */

public class RepayDetailActivity extends BaseActivity implements RepayDetailListPresenter.View, View.OnClickListener {

	private static final int LOADER_ID = 1;
	public static final int FRAGMENT_MULTI_REPAY_DETAIL = 1;
	public static final int FRAGMENT_SINGLE_REPAY_DETAIL = 2;
	public static final String KEY_BUNDLE_ARG_REPAY_DETAIL_LIST = "key_bundle_arg_repay_detail_list";
	public static final String KEY_INTENT_LOAN_NO = "key_intent_loan_no";
	public static final String KEY_INTENT_TYPE = "key_intent_type";


	private RepayDetailListPresenter mPresenter;
	private View mNetWorkFailedView;
	private TextView mRetryTv;
	private String mCurrentLoanNo = "";
	private String mCurrentType = "";
	private ArrayList<BaseFragment> fragmentList = new ArrayList<>();

	public static void start(Activity aty, String loanNo, String currentType) {
		Intent intent = new Intent(aty, RepayDetailActivity.class);
		intent.putExtra(KEY_INTENT_LOAN_NO, loanNo);
		intent.putExtra(KEY_INTENT_TYPE, currentType);
		aty.startActivity(intent);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_repay_detail);
		setTitle(R.string.repay_detail);
		mNetWorkFailedView = findViewById(R.id.no_network_layout);
		mRetryTv = (TextView) findViewById(R.id.retry_tv);
		mNetWorkFailedView.setOnClickListener(this);
		getSupportLoaderManager().initLoader(LOADER_ID, null, this);
	}

	public void showFragment(int page, ArrayList<RepayDetailListModel.Repay.RepayDetail> detail) {
		FragmentManager fm = getSupportFragmentManager();
		FragmentTransaction ft = fm.beginTransaction();
		ft.setCustomAnimations(R.anim.slide_right_in, R.anim.slide_left_out, R.anim.slide_left_in, R.anim.slide_right_out);
		switch (page) {
			case FRAGMENT_MULTI_REPAY_DETAIL:
				if (fragmentList.size() > 0 && fragmentList.get(fragmentList.size() - 1) instanceof MultiRepayDetailFragment) {
					(((MultiRepayDetailFragment) fragmentList.get(fragmentList.size() - 1))).setData(detail);
					return;
				}
				MultiRepayDetailFragment multiRepayDetailFragment = MultiRepayDetailFragment.newInstance(detail);
				ft.addToBackStack(MultiRepayDetailFragment.class.getSimpleName());
				ft.add(R.id.repay_detail_container, multiRepayDetailFragment, MultiRepayDetailFragment.class.getSimpleName());
				fragmentList.add(multiRepayDetailFragment);
				break;
			case FRAGMENT_SINGLE_REPAY_DETAIL:
				if (fragmentList.size() > 0 && fragmentList.get(fragmentList.size() - 1) instanceof SingleRepayDetailFragment) {
					(((SingleRepayDetailFragment) fragmentList.get(fragmentList.size() - 1))).setData(detail);
					return;
				}
				SingleRepayDetailFragment singleRepayDetailFragment = SingleRepayDetailFragment.newInstance(detail, mCurrentLoanNo);
				ft.addToBackStack(SingleRepayDetailFragment.class.getSimpleName());
				ft.add(R.id.repay_detail_container, singleRepayDetailFragment, SingleRepayDetailFragment.class.getSimpleName());
				fragmentList.add(singleRepayDetailFragment);
				break;
			default:
				break;
		}
		ft.commitAllowingStateLoss();
	}

	@Override
	public Loader<Presenter> onCreateLoader(int id, Bundle args) {
		return new PresenterLoader<>(this, new RepayDetailListPresenter.Generator());
	}

	@Override
	public void onLoadFinished(Loader<Presenter> loader, Presenter data, int placeholder) {
		mPresenter = (RepayDetailListPresenter) data;
		mPresenter.attach(this);
		mCurrentLoanNo = getIntent().getStringExtra(KEY_INTENT_LOAN_NO);
		mCurrentType = getIntent().getStringExtra(KEY_INTENT_TYPE);
		RequestRepayDetailListEvent event = new RequestRepayDetailListEvent();
		event.loanNo = mCurrentLoanNo;
		event.type = mCurrentType;
		requestRepayDetailList(event);
	}

	@Override
	public void getRepayDetailSuccess(String type, ArrayList<RepayDetailListModel.Repay.RepayDetail> detail) {
		mNetWorkFailedView.setVisibility(View.GONE);
		switch (type) {
			case RepayDetailListPresenter.TYPE_SINGLE_REPAY_DETAIL:
				showFragment(FRAGMENT_SINGLE_REPAY_DETAIL, detail);
				break;
			case RepayDetailListPresenter.TYPE_NO_ID_CARD:
			case RepayDetailListPresenter.TYPE_MULTI_REPAY_DETAIL:
				showFragment(FRAGMENT_MULTI_REPAY_DETAIL, detail);
				break;
			default:
				break;
		}
	}

	@Override
	public void obtainRepayListFailed(String tips) {
		// 网络错误, 显示网络异常界面
		mNetWorkFailedView.setVisibility(View.VISIBLE);
	}

	@Override
	public void onFunctionalError(Throwable e, boolean autoTips, int functionalCode) {
		super.onFunctionalError(e, autoTips, functionalCode);
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				// 网络错误, 显示网络异常界面
				mNetWorkFailedView.setVisibility(View.VISIBLE);
			}
		});
	}

	@Override
	public void onClick(View v) {
		super.onClick(v);
		switch (v.getId()) {
			case R.id.no_network_layout:
				// 网络错误, 点击网络异常界面重试.
				RequestRepayDetailListEvent event = new RequestRepayDetailListEvent();
				event.loanNo = mCurrentLoanNo;
				event.type = mCurrentType;
				requestRepayDetailList(event);
				break;
			default:
				break;
		}
	}

	@Override
	protected void onBackBtnPressed() {
		doBack();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// 判断当前按键是返回键
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			doBack();
		}
		return true;
	}

	/**
	 * 根据Fragment栈回退.
	 */
	private void doBack() {
		if (fragmentList.size() > 1) {
			FragmentManager fm = getSupportFragmentManager();
			fm.popBackStackImmediate();

			fragmentList.remove(fragmentList.size() - 1);
		} else {
			finish();
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		getSupportLoaderManager().destroyLoader(LOADER_ID);
	}

	@Subscribe(threadMode = ThreadMode.MAIN)
	public void requestRepayDetailList(RequestRepayDetailListEvent event) {
		mCurrentLoanNo = event.loanNo;
		mCurrentType = event.type;
		mPresenter.getRepayDetailList(event.loanNo, event.type);
	}

	static class RequestRepayDetailListEvent {
		String loanNo = "";
		String type = "";
	}
}
